package com.zc.service_sms.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.zc.commonutils.Constants;
import com.zc.service_sms.service.SmsService;
import com.zc.service_sms.utils.ConstantSmsUtils;
import com.zc.service_sms.utils.RandomUtil;
import com.zc.service_sms.utils.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class SmsServiceImpl implements SmsService {


    private ConstantSmsUtils constantSmsUtils;
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public SmsServiceImpl(ConstantSmsUtils constantSmsUtils, StringRedisTemplate stringRedisTemplate) {
        this.constantSmsUtils = constantSmsUtils;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean send(String phone) throws Exception {
        String code = RandomUtil.getFourBitRandom();
stringRedisTemplate.opsForValue().set(Constants.LOGIN_CODE_KEY+phone,code,Constants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        Client client = Sample.createClient(constantSmsUtils.getKeyid(), constantSmsUtils.getKeysecret());
        SendSmsRequest sendReq = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("小汪的博客")
                .setTemplateCode("SMS_271625461")
                .setTemplateParam("{\"code\":\"" + code + "\"}");
        SendSmsResponse sendResp = client.sendSms(sendReq);
        String codeResp = sendResp.body.code;
        if (!com.aliyun.teautil.Common.equalString(codeResp, "OK")) {
            com.aliyun.teaconsole.Client.log("错误信息: " + sendResp.body.message + "");
            return false;
        }
        return true;
    }
}
